<!--
 * @Description: 
 * @Version: @1.0.0
 * @Autor: LuLu
 * @Date: 2022-09-01 16:00:58
 * @LastEditors: LuLu
 * @LastEditTime: 2022-09-15 16:33:42
-->
<template>
  <div>
    <div class="app-container">
      <div class="mb8">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="AddModify"
          v-hasPermi="['contract:add']"
          >新增</el-button
        >

        <div class="export" @click="Export">导出</div>
      </div>
      <div style="margin-bottom: 10px">
        <el-input
          style="width: 200px;  margin-right: 10px; margin-bottom: 10px"
          v-model="searchContract"
          placeholder="请输入合同号"
          @change="selectChanged"
          clearable
        ></el-input>
        <el-input
          style="width: 200px; margin-right: 10px; margin-bottom: 10px"
          v-model="searchTitle"
          placeholder="请输入客户/供应商名称"
          @change="selectChanged"
          clearable
        ></el-input>
        <el-input
          style="width: 200px; margin-right: 10px; margin-bottom: 10px"
          v-model="searchCreator"
          placeholder="请输入创建人"
          @change="selectChanged"
          clearable
        ></el-input>
        <!-- <el-select
          v-model="searchBusinessType"
          placeholder="请选择业务类型"
          clearable
          style="width: 200px; margin-right: 10px; margin-bottom: 10px"
        >
          <el-option
            v-for="dict in businessOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select> -->
        <el-date-picker style="width: 300px; margin-right: 10px; margin-bottom: 10px"
          v-model="searchTime"
          type="daterange"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          @click="getContractList"
          >搜索</el-button
        >
      </div>

      <el-table :data="contractList">
        <el-table-column
          property="contractNo"
          label="合同号"
          align="center"
          width="180"
        ></el-table-column>

        <el-table-column property="createBy" label="创建者" align="center" width="120"></el-table-column>
        <el-table-column label="合同签订主体" align="center" prop="mainBody" width="280">
          <template slot-scope="scope">
            <dict-tag :options="bodyOptions" :value="scope.row.mainBody"/>
          </template>
        </el-table-column>

        <el-table-column
          property="contractTitle"
          label="客户/供应商名称"
          align="center"
        ></el-table-column>
        <!-- <el-table-column property="contractAmount" label="合同金额" align="center" width="120"></el-table-column>
        <el-table-column label="结算币种" align="center" width="120" prop="currency">
          <template slot-scope="scope">
            <dict-tag :options="currencyOptions" :value="scope.row.currency"/>
          </template>
        </el-table-column> -->

        <!-- <el-table-column label="业务类型" align="center" width="120" prop="businessType">
          <template slot-scope="scope">
            <dict-tag :options="businessOptions" :value="scope.row.businessType + ''"/>
          </template>
        </el-table-column> -->

        <!-- <el-table-column
          property="contractDesc"
          label="简介"
          :show-overflow-tooltip="true"
        ></el-table-column> -->
        <el-table-column
          property="contractRemark"
          label="备注"
          align="center"
          width="120"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ FormatTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column property="status" label="状态" align="center" width="80">
          <template slot-scope="{ row }">
            <el-tag v-if="row.status == 0">待审核</el-tag>
            <el-tag type="success" v-if="row.status == 1">通过</el-tag>
            <el-tag type="warning" v-if="row.status == 2">打回</el-tag>
            <el-tag type="info" v-if="row.status == 3">作废</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="240"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-if="scope.row.status == 0 || scope.row.status == 2"
              @click="AddModify(scope.row)"
              v-hasPermi="['contract:update']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-close"
              v-if="scope.row.status == 0 || scope.row.status == 2"
              @click="setCancel(scope.row)"
              v-hasPermi="['contract:delete']"
              >报废</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-refresh-left"
              v-if="scope.row.status == 0"
              @click="setReject(scope.row)"
              v-hasPermi="['contract:reject']"
              >打回</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-check"
              v-if="scope.row.status == 0"
              @click="setAdopt(scope.row)"
              v-hasPermi="['contract:success']"
              >通过</el-button
            >
            <el-button
              size="mini"
              type="text"
              v-if="scope.row.status == 1 || scope.row.status == 3"
              >--</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <div class="block" style="margin: 20px">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="queryData.page"
          :page-size.sync="queryData.pagesize"
          :page-sizes="[2, 4, 6, 8, 10]"
          small
          layout="prev, pager, next"
          :total="queryData.total"
        >
        </el-pagination>
      </div>
      <!-- 添加或修改对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="open"
        width="480px"
        append-to-body
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="130px">
          <el-form-item label="类型" v-show="editFlag" prop="tradeType">
            <el-select
              v-model="form.tradeType"
              placeholder="请选择类型"
              style="width: 258px"
              @change="getTradeName"
            >
              <el-option
                v-for="dict in tradeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="客户/供应商名称" prop="contractTitle" v-show="editFlag">
            <el-input v-if="!nameShow" v-model="form.contractTitle" placeholder="必须是全称" style="width: 260px;"/>
            <el-select v-else v-model="form.contractTitle" filterable placeholder="请选择" :filter-method="filterTrade" style="width: 258px" @change="optionChange">
              <el-option
                v-for="item in filterNameOptions"
                :key="item.id"
                :label="item.companyName"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="合同签订主体" prop="mainBody" v-show="editFlag">
              <el-select
                v-model="form.mainBody"
                placeholder="请选择合同签订主体"
                clearable
                style="width: 258px"
              >
              <el-option
                  v-for="dict in bodyOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          <!-- <el-form-item label="业务类型" prop="businessType" v-show="editFlag">
              <el-select
                v-model="form.businessType"
                placeholder="请选择业务类型"
                clearable
                style="width: 258px"
              >
                <el-option
                  v-for="dict in businessOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item> -->
          <!-- <el-form-item label="合同金额" prop="contractAmount">
            <el-input style="width: 258px"
              type="number"
              v-model="form.contractAmount"
              placeholder="请输入合同金额"
            />
          </el-form-item>
          <el-form-item label="币种" prop="currency">
            <el-select
              v-model="form.currency"
              placeholder="请选择结算币种"
              style="width: 258px"
            >
              <el-option
                v-for="dict in currencyOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="备注" prop="contractRemark">
            <el-input style="width: 258px"
              type="textarea"
              v-model="form.contractRemark"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 饼状图 -->
    <el-row class="app-container" style="margin-top: 15px">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <div id="monthData" class="curveData"></div></div
      ></el-col>
      <el-col :span="12"
        ><div class="grid-content bg-purple-light">
          <div id="totalData" class="curveData"></div></div
      ></el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {
  getContract,
  addContract,
  modifyContract,
  setSuccess,
  setReject,
  setCancel,
  getStatistic,
  getExport,
  getTradeName,
} from "@/api/contract";
export default {
  name: "Contract",
  data() {
    return {
      contractList: [], //合同列表信息保存
      // 分页
      queryData: {
        page: 1, // 当前页码
        pagesize: 10,
        total: 0, // 总数
      },
      //   表单参数
      form: {
        contractTitle: ""
      },
      editFlag: true,
      businessOptions: [],
      tradeOptions: [],
      currencyOptions: [],
      bodyOptions: [],
      tradeNameList: [],
      nameOptions: [],
      filterNameOptions: [],
      nameShow: true,
      // 表单title
      title: "",
      // 是否显示弹出层
      open: false,
      rules: {
        tradeType: [
          { required: true, trigger: "blur", message: "客户群体不能为空" },
        ],
        contractTitle: [
          { required: true, trigger: "blur", message: "供应商不能为空" },
        ],
        businessType: [
          { required: true, trigger: "change", message: "业务类型不能为空" },
        ],
        mainBody: [
          { required: true, trigger: "change", message: "合同主体不能为空" },
        ],
        contractAmount: [
          { required: true, trigger: "change", message: "合同金额不能为空" },
        ],
      },
      searchContract: "", //搜索合同号
      searchTitle: "", //搜索标题
      searchCreator:"",
      searchBusinessType: "", //搜索业务类型
      searchTime:[]
    };
  },
  created() {
    this.getDicts("business_type").then(response => {
      this.businessOptions = response.data;
    });
    this.getDicts("main_body_code").then(response => {
      this.bodyOptions = response.data;
      this.bodyOptions = this.bodyOptions.filter(function(item) {
        return item.dictValue !== "Z"
      });
    });
    this.getDicts("trade_type").then(response => {
      this.tradeOptions = response.data;
    });
    this.getDicts("currency").then(response => {
      this.currencyOptions = response.data;
    });
    let res = getTradeName();
    res.then(ress =>{
      this.tradeNameList = ress.data
    })
    
  },
  mounted() {
    // 获取合同列表信息保存
    this.getContractList();
    // // 月饼状图
    this.getMonthData();
    // // 总饼状图
    this.getTotalData();
    // 饼状图数据
    this.getStatistic();
  },
  methods: {
    getTradeName(value){
      if(value == 3) {
        this.nameShow = false
      } else {
        if(value == 1) {
          this.nameOptions = this.tradeNameList[0]
        } else {
          this.nameOptions = this.tradeNameList[1]
        }
        this.filterNameOptions = this.nameOptions.slice(0, 100) // 只显示前100条
        this.nameShow = true
      }
    },
    // 自定义el-select的搜索实现方法
    filterTrade(value) {
        const list = this.nameOptions.filter(item => {
          return item.companyName && item.companyName.toUpperCase().includes(value.toUpperCase())
        })
        // 根据检索条件筛选出来的选项，只取前30条
        if (list.length > 100) {
          this.filterNameOptions = list.slice(0, 100)
        } else {
          this.filterNameOptions = list
        }
    },
    optionChange(value){
      console.log(value)
      this.form.customerId = value.id
      this.form.contractTitle = value.companyName
    },
    // 数据导出
    async Export() {
      this.$confirm("是否确认导出合同资源?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let beginTime = '';
          let endTime = '';
          if (this.searchTime) {
            beginTime = this.searchTime[0];
            endTime = this.searchTime[1];
          }
          let query = {
            contractNo: this.searchContract, //合同号
            contractTitle: this.searchTitle, //标题
            createBy: this.searchCreator,
            businessType: this.searchBusinessType,
            pageNum: this.queryData.page,
            pageSize: this.queryData.pagesize,
            beginTime: beginTime,
            endTime: endTime
          };
          return getExport(query);
        })
        .then((response) => {
          console.log(response);
          this.download(response.msg);
        })
        .catch(function () {});
      // const res = await getExport();
      // console.log(999, res);
      // let url = window.URL.createObjectURL(
      //   new Blob([res], { type: "application/vnd.ms-excel" })
      // );
      // let link = document.createElement("a");
      // link.style.display = "none";
      // link.href = url;
      // link.setAttribute("download", "合同列表" + ".xls");
      // document.body.appendChild(link);
      // link.click();
    },
    selectChanged() {
      this.getContractList();
    },

    // 获取合同列表信息
    async getContractList() {
      let beginTime = '';
      let endTime = '';
      if (this.searchTime) {
        beginTime = this.searchTime[0];
        endTime = this.searchTime[1];
      }
      let query = {
        contractNo: this.searchContract, //合同号
        contractTitle: this.searchTitle, //标题
        createBy: this.searchCreator,
        businessType: this.searchBusinessType,
        pageNum: this.queryData.page,
        pageSize: this.queryData.pagesize,
        beginTime: beginTime,
        endTime: endTime
      };
      
      let res = await getContract(query);
      this.queryData.total = res.total;
      this.contractList = res.rows;
    },
    // 分页
    handleSizeChange(val) {
      this.queryData.pagesize = val;
      this.getContractList();
    },
    handleCurrentChange(val) {
      this.queryData.page = val;
      this.getContractList();
    },
    // 新增 /修改
    AddModify(row) {
      this.open = true;
      if (row.id) {
        this.title = "编辑合同";
        this.form = row;
        this.editFlag = false;
      } else {
        this.$notify({
          message: '合同号已由系统生成',
          type: 'success',
          customClass: "messageIndex",
        });
        // this.$message({
        //   message: "合同号已由系统生成",
        //   type: "success",
        //   customClass: "messageIndex",
        // });
        this.form = {};
        this.title = "新增合同";
        this.editFlag = true;
      }
    },
    // 修改
    // handleUpdate() {},
    // 确定
    async submitForm() {
      console.log(this.form)
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            modifyContract(this.form).then((response) => {
              this.$message({
                type: "success",
                message: "修改成功",
              });
              this.open = false;
              this.getContractList();
            });
          } else {
            this.$confirm("新增合同", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(async () => {
                await addContract(this.form);
                this.$message({
                  type: "success",
                  message: "新增成功",
                });
                this.open = false;
                this.getContractList();
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消",
                });
                this.open = false;
              });
          }
        }
      });
    },
    // 取消
    cancel() {
      this.open = false;
      this.form = {};
    },

    //审核 通过合同
    async setAdopt(row) {
      await this.$confirm("通过合同,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let query = {
            id: row.id,
          };
          await setSuccess(query);
          this.$message({
            type: "success",
            message: "已通过",
          });
          this.getContractList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
          this.getContractList();
        });
    },
    // 审核  拒绝合同
    async setReject(row) {
      await this.$confirm("拒绝合同,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let query = {
            id: row.id,
          };
          await setReject(query);
          this.$message({
            type: "success",
            message: "已拒绝",
          });
          this.getContractList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
          this.getContractList();
        });
    },
    // 审核 报废合同
    async setCancel(row) {
      await this.$confirm("报废合同,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let query = {
            id: row.id,
          };
          await setCancel(query);
          this.$message({
            type: "success",
            message: "已报废",
          });
          this.getContractList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
          this.getContractList();
        });
    },
    // 饼状图数据获取
    async getStatistic() {
      let res = await getStatistic();
      this.getMonthData(res.data.month);
      this.getTotalData(res.data.total);
    },
    // 月饼状图
    getMonthData(data) {
      const myChart = echarts.init(document.getElementById("monthData"));
      myChart.setOption({
        title: {
          text: "月度占比",
          // subtext: "Fake Data",
          // left: "center",
        },
        // 悬浮提示
        tooltip: {
          show: true,
          trigger: "item",
          backgroundColor: "#656565",
          textStyle: { color: "#ffffff" },
          extraCssText: "box-shadow: 0px 2px 5px 0px rgba(50,107,174,0.19);",
        },
        legend: {
          top: '5%'
          // orient: "vertical",
          // left: "left",
        },
        grid: {
        left: '3%',     //图表距离左右上下之间的距离
        right: '4%',
        top: '15%',
        bottom: '13%',
        containLabel: true
    },
        series: [
          {
            name: "月度占比",
            type: "pie",
            radius: "70%",
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      });
    },
    // 总饼状图
    getTotalData(data) {
      const myChart = echarts.init(document.getElementById("totalData"));
      myChart.setOption({
        title: {
          text: "总占比",
          // subtext: "Fake Data",
          // left: "center",
        },
        // 悬浮提示
        tooltip: {
          show: true,
          trigger: "item",
          backgroundColor: "#656565",
          textStyle: { color: "#ffffff" },
          extraCssText: "box-shadow: 0px 2px 5px 0px rgba(50,107,174,0.19);",
        },
        legend: {
          top: '5%'
          // orient: "vertical",
          // left: "left",
        },
        series: [
          {
            name: "总占比",
            type: "pie",
            radius: "70%",
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      });
    },
  },
};
</script>

<style  scoped>
.app-container {
  margin-top: 5px;
  border: 1px solid #eee;
  box-shadow: 0 1px 3px 0 rgb(0 0 0 / 3%), 0 0 3px 0 rgb(0 0 0 / 4%);
}
.block {
  display: flex;
  justify-content: end;
}
.messageIndex {
  z-index: 999999999 !important;
}
/* 饼状图 */
.curveData {
  height: 560px;
}
.mb8 {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}
.export {
  width: 70px;
  height: 36px;
  border-radius: 4px;
  border: 1px solid #dddfe6;
  font-size: 14px;
  text-align: center;
  line-height: 36px;
  cursor: pointer;
}
</style>
<style>
  .el-message-box {
    width: 375px;
  }
</style>